package com.springboot.mall.service.impl;

import com.springboot.mall.exception.MallException;
import com.springboot.mall.exception.MallExceptionEnum;
import com.springboot.mall.model.entity.User;
import com.springboot.mall.model.mappers.UserMapper;
import com.springboot.mall.service.UserService;
import com.springboot.mall.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

/*
 *
 *
 *@data 2022-05-07
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    //这个使用的最多
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUser() {
        User zhuzhu = userMapper.selectByName("zhuzhu");
        return zhuzhu;
    }

    @Override
    public void register(String userName, String password) throws
    MallException {
        //重名校验
        //service不应该处理返回信息，所以这里需要使用异常
        User result = userMapper.selectByName(userName);
        //重名
        if (result != null){
                throw new MallException(MallExceptionEnum.NAME_EXISTED);
        }
        //写到数据库
        User user = new User();
        user.setUsername(userName);
        try {
            user.setPassword(MD5Utils.getMD5Str(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        int count = userMapper.insertSelective(user);
        if (count == 0){
            throw  new MallException(MallExceptionEnum.INSERT_FAILED);
        }

    }

    @Override
    public User login(String userName, String password) throws MallException {
        String md5Password = null;
        //他的判断逻辑不一样，前面SSM的逻辑更加清晰，更好理解,不过他的更加安全
        try {
            md5Password = MD5Utils.getMD5Str(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        User user = userMapper.selectLogin(userName, md5Password);
        if (user == null){
            throw new MallException(MallExceptionEnum.WRONG_PASSWORD);
        }
        return user;
    }

    @Override
    public void updateInfo(User user) throws MallException {
        //更新个性签名
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 1){
            throw new MallException(MallExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public boolean checkAdminRole(User user){
        //1.普通用户 2.管理员
        return user.getRole().equals(2);
    }


}
